import 'package:flutter/material.dart';
import 'package:http/http.dart'; // For connecting to an Ethereum node
import 'package:web3dart/web3dart.dart';

class RentContractApp extends StatefulWidget {
  @override
  _RentContractAppState createState() => _RentContractAppState();
}

class _RentContractAppState extends State<RentContractApp> {
  late Web3Client _client;
  final String _rpcUrl =
      'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'; // 使用Infura或本地节点URL
  final String _privateKey = 'YourPrivateKey'; // 你的以太坊钱包私钥
  late Credentials _credentials;
  late EthereumAddress _contractAddress;
  late DeployedContract _contract;
  late ContractFunction _payRent;
  late ContractFunction _checkOverdue;
  late EthereumAddress _tenantAddress;

  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initializeWeb3();
  }

  Future<void> _initializeWeb3() async {
    // 初始化客户端
    _client = Web3Client(_rpcUrl, Client());

    // 加载钱包凭证
    _credentials = EthPrivateKey.fromHex(_privateKey);
    _tenantAddress = await _credentials.extractAddress();

    // 合约地址
    _contractAddress = EthereumAddress.fromHex('0xYourContractAddress');

    // 加载合约的ABI并找到相关方法
    String abi = '''[
      {
        "constant": false,
        "inputs": [],
        "name": "payRent",
        "outputs": [],
        "type": "function"
      },
      {
        "constant": true,
        "inputs": [],
        "name": "checkOverdue",
        "outputs": [{"name": "", "type": "bool"}],
        "type": "function"
      }
    ]''';

    // 部署合约
    _contract = DeployedContract(
      ContractAbi.fromJson(abi, 'RentalAgreement'),
      _contractAddress,
    );

    // 获取合约方法
    _payRent = _contract.function('payRent');
    _checkOverdue = _contract.function('checkOverdue');

    setState(() {
      _isLoading = false;
    });
  }

  Future<void> _payRentFunction() async {
    // 调用支付租金的智能合约函数
    final transaction = Transaction.callContract(
      contract: _contract,
      function: _payRent,
      from: _tenantAddress,
      value: EtherAmount.fromUnitAndValue(EtherUnit.ether, 1),
      // 例如1 ETH支付租金
      gasPrice: EtherAmount.inWei(BigInt.one),
      parameters: [],
    );

    await _client.sendTransaction(_credentials, transaction, chainId: 1);
  }

  Future<void> _checkOverdueFunction() async {
    // 检查合同是否过期
    var isOverdue = await _client.call(
      contract: _contract,
      function: _checkOverdue,
      params: [],
    );
    print("合同是否过期: $isOverdue");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Rental Contract'),
        ),
        body: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton(
                    onPressed: _payRentFunction,
                    child: const Text('Pay Rent'),
                  ),
                  ElevatedButton(
                    onPressed: _checkOverdueFunction,
                    child: const Text('Check Overdue'),
                  ),
                ],
              ),
      ),
    );
  }

  @override
  void dispose() {
    _client.dispose();
    super.dispose();
  }
}
